package com.zt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zt.common.BusinessException;
import com.zt.entity.Admin;
import com.zt.service.AdminService;
import com.zt.mapper.AdminMapper;
import com.zt.utils.JwtUtils;
import com.zt.vo.LoginVO;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
* @author unmai
* @description 针对表【admin】的数据库操作Service实现
* @createDate 2025-04-25 13:45:46
*/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{

    private static final String SALT = "tutoradmin";

    // admin 对应的密码为 123456
    @Override
    public LoginVO login(String username, String password) {
        // 1. 查询用户
        LambdaQueryWrapper<Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername, username);
        Admin admin = this.getOne(wrapper);

        if (admin == null) {
            throw new BusinessException("用户名或密码错误");
        }

        System.out.println(password);
        // 2. 验证密码
        String encryptedPassword = DigestUtils.md5DigestAsHex((password + SALT).getBytes());
        System.out.println(encryptedPassword);
        if (!encryptedPassword.equals(admin.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }

        // 3. 检查状态
        if (admin.getStatus() != null && admin.getStatus() == 0) {
            throw new BusinessException("账号已被禁用");
        }

        // 4. 生成token
        String token = JwtUtils.generateToken(admin.getId());

        // 5. 返回登录信息
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        loginVO.setName(admin.getName());
        return loginVO;
    }

    @Override
    public Admin getCurrentAdmin() {
        Integer adminId = JwtUtils.getCurrentUserId();
        if (adminId == null) {
            throw new BusinessException("未登录");
        }
        return this.getById(adminId);
    }

    @Override
    public boolean updatePassword(String oldPassword, String newPassword) {
        // 1. 获取当前登录用户
        Admin admin = getCurrentAdmin();
        if (admin == null) {
            throw new BusinessException("未登录");
        }

        // 2. 验证旧密码
        String encryptedOldPassword = DigestUtils.md5DigestAsHex((oldPassword + SALT).getBytes());
        if (!encryptedOldPassword.equals(admin.getPassword())) {
            throw new BusinessException("旧密码错误");
        }

        // 3. 更新新密码
        String encryptedNewPassword = DigestUtils.md5DigestAsHex((newPassword + SALT).getBytes());
        admin.setPassword(encryptedNewPassword);
        return this.updateById(admin);
    }

    @Override
    public void logout() {
        // 由于使用的是JWT，服务端不需要额外的处理
        // 客户端需要清除token即可
        // 这里可以添加一些额外的清理工作，比如记录日志等
    }
}




